package com.tx.schedule.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.tx.schedule.factory.ScheduleJobFactory;
import com.tx.schedule.model.ScheduleJob;
import com.tx.schedule.service.ScheduleService;

@Controller
@RequestMapping(value = "/schedule")
public class ScheduleController {
	@Autowired
	private ScheduleService scheduleService;

	/**
	 * 获取所有调度器列表
	 * 
	 * @return
	 */
	@RequestMapping(value = "/listAll", method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> getAllSchedule(int start, int end) {
		Map<String, Object> resultMap = new HashMap<>();
		List<ScheduleJob> list = scheduleService.getScheduleJobs(start, end);
		resultMap.put("data", list);
		resultMap.put("total", list.size());
		resultMap.put("result", "SUCCESS");
		return resultMap;
	}

	/**
	 * 获取指定任务，用于查看或编辑
	 * 
	 * @param jobId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getById", method = RequestMethod.GET)
	public ScheduleJob getById(String jobId) {
		return scheduleService.getScheduleJobById(jobId);
	}

	/**
	 * 删除(物理)任务，成功返回SUCCESS,失败返回FAIL
	 * 
	 * @param jobId
	 * @return
	 */
	@RequestMapping(value = "/deleteJob", method = RequestMethod.GET)
	@ResponseBody
	public String deleteScheduleJob(String jobId) {
		int effect = scheduleService.deleteSchedule(jobId);
		return effect > 0 ? "SUCCESS" : "FAIL";
	}

	/**
	 * 更新任务
	 * 
	 * @param scheduleJob
	 * @return
	 */
	@RequestMapping(value = "/updateJob", method = RequestMethod.POST)
	@ResponseBody
	public String updateScheduleJob(ScheduleJob scheduleJob) {
		if(!ScheduleJobFactory.isValidExpression(scheduleJob))
			return "expression invalid";
		int effect = scheduleService.updateSchedule(scheduleJob);
		return effect > 0 ? "SUCCESS" : "FAIL";
	}

	/**
	 * 添加任务
	 * 
	 * @param scheduleJob
	 * @return
	 */
	@RequestMapping(value = "/addJob", method = RequestMethod.POST)
	@ResponseBody
	public String addScheduleJob(ScheduleJob scheduleJob) {
		if(!ScheduleJobFactory.isValidExpression(scheduleJob))
			return "expression invalid";
		int effect = scheduleService.insertScheduler(scheduleJob);
		return effect > 0 ? "SUCCESS" : "FAIL";
	}
}
